<?php
// -----------------------------------------------------------------------------
// include
// -----------------------------------------------------------------------------

include "../config/config.php";
include "../auth.php";
include "../DBManager.php";
include "../resources/Snowflake/HighConcurrencySnowflake.php";

// -----------------------------------------------------------------------------
// 访问设置
// -----------------------------------------------------------------------------

if (!isset($_POST["linkId"]) ||
    !isset($_POST["linkTitle"]) ||
    !isset($_POST["linkUrl"]) ||
    !isset($_POST["categoryId"]) ||
    !isset($_POST["linkDescription"])) {
    exit("需要传入有效的参数！");
}

$linkId = $_POST['linkId'];
$title = $_POST["linkTitle"];
$url = $_POST["linkUrl"];
$description = $_POST["linkDescription"];
$categoryId = $_POST["categoryId"];

$sortNumber = "";
$timeLastEdit = "";
$timeLastMove = "";

// -----------------------------------------------------------------------------
// 时区设置
// -----------------------------------------------------------------------------

date_default_timezone_set($region);
$timeLastEdit = (string)time();

// -----------------------------------------------------------------------------
// 数据库相关设置
// -----------------------------------------------------------------------------

$dbPath = "../" . $dbPath;
$db = new DBManager("sqlite:" . $dbPath);

// -----------------------------------------------------------------------------

/* 判断链接是否存在 */
if (!$db->checkIfLinkExistsById($linkId)) {
    exit("修改失败，因为指定的「链接id」不存在！");
}

/* 判断是否变更了分类 */
$linkDetails = $db->getLinkDetailsById($linkId);
if ($linkDetails["categoryId"] != $categoryId) { // 这里不能使用 !== 运算符比较
    // 变更了分类，那么也应该修改链接的排序号。
    // 使用雪花算法，根据当前时间戳生成排序号，这样链接就会出现在相应分类的最下方，方便定位。
    $snowflake = new HighConcurrencySnowflake();
    $sortNumber = $snowflake->nextId();

    // 记录分类转移时间
    $timeLastMove = $timeLastEdit;
} else {
    // 没有变更分类，那么，还是使用原来的排序号。
    $sortNumber = $linkDetails["sortNumber"];
    // 没有变更分类，$timeLastMove 还是使用原来的值
    $timeLastMove = $linkDetails["timeLastMove"];
}

// -----------------------------------------------------------------------------

$arr = compact("title", "url", "sortNumber", "description", "categoryId", "timeLastEdit", "timeLastMove");

$db->updateLink($linkId, $arr);
echo "修改成功！";
